package com.complaint.rest.dao;

import com.complaint.rest.Complaints;
import com.complaint.rest.em.EMF;
import com.complaint.rest.helper.IdHelper;
import com.complaint.rest.model.Complaint;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;

/**
 * Created by Alex
 */
public class ComplaintDAOImpl implements ComplaintDAO {
    private EntityManager entityManager = EMF.get().createEntityManager();

    @Override
    public Complaint addComplaint(Complaint complaint) {
        Complaint persistedComplaint = new Complaint(
                IdHelper.get(),
                complaint.getAuthorId(),
                complaint.getSubject(),
                complaint.getDescription(),
                complaint.getPublishDate()
        );
        entityManager.getTransaction().begin();
        entityManager.persist(persistedComplaint);
        entityManager.getTransaction().commit();
        return persistedComplaint;
    }

    @Override
    public void removeComplaint(Complaint complaint) {
        entityManager.getTransaction().begin();
        entityManager.remove(complaint);
        entityManager.getTransaction().commit();
    }

    @Override
    public void updateComplaint(Complaint complaint) {
        entityManager.getTransaction().begin();
        entityManager.persist(complaint);
        entityManager.getTransaction().commit();
    }

    @Override
    public Complaint getComplaint(String id) {
        return entityManager.find(Complaint.class, id);
    }

    @Override
    public List<Complaint> getComplaintsByUserId(String id) {
        Query query = entityManager.createQuery("SELECT c FROM Complaint c WHERE c.authorId = :authorId").setParameter("authorId", id);
        return new Complaints(query.getResultList());
    }

    @Override
    public List<Complaint> listComplaints() {
        Query query = entityManager.createQuery("SELECT c FROM Complaint c ORDER BY c.id");
        return new Complaints(query.getResultList());
    }
}
